#include "singleLinkedList.h"

ND *createList()
{
    ND *header = (ND *)malloc(sizeof(ND));
    ERROR_CHECK(NULL, header, "malloc");
    header->next = NULL;
    return header;
}
void insertNodeTail(ND *header, type val)
{
    ND *p = header;
    while (p->next)
    {
        p = p->next;
    };
    ND *new_node = (ND *)malloc(sizeof(ND));
    ERROR_CHECK(NULL, new_node, "mallocTail");

    new_node->data = val;
    new_node->next = NULL;
    p->next = new_node;
}
void insertNodeHead(ND *header, type val)
{
    ND *new_node = (ND *)malloc(sizeof(ND));
    ERROR_CHECK(NULL, new_node, "mallocHeadnewHead");
    new_node->data = val;
    new_node->next = header->next;
    header->next = new_node;
}
void showList(ND *header)
{
    if (NULL == header)
    {
        printf("List is NULL\n");
        exit(1);
    }
    while (header = header->next)
    {
        printf("%d ", header->data);
    }
    puts("");
}
// void showList2(ND header){
//      ND p = header;

//     while (p.next != NULL)
//     {
//         p = *p.next;
//         printf("%d ",p.data);
//     }
//     puts("");
// }
void delNode1(ND *header, int val)
{

    while (header->next)
    {
        if (header->next->data == val)
            break;
        header = header->next;
    }
    if (header->next)
    {
        ND *temp = header->next;
        header->next = temp->next;
        free(temp);
    }
}
void delNode0(ND *header, int val)
{
    ND *pVal = header->next;
    ND *pCur = NULL;
    if (pVal->data == val)
    {
        header->next = pVal->next;
        free(pVal);
        return;
    }
    while ((pVal != NULL) && (pVal->data != val))
    {
        pCur = pVal;
        pVal = pVal->next;
    }
    if (pVal == NULL)
    {
        puts("not found");
    }
    else
    {
        ND *temp = pCur->next;
        pCur->next = pCur->next->next;
        free(temp);
    }
    // return delNode(header,val);
}
int lengthList(ND *header)
{
    int ret = 0;
    while (header = header->next)
    {
        ret++;
    }
    return ret;
}
int isEmptyList(ND *header)
{
    if (NULL == header)
    {
        puts("NULL list");
        exit(1);
    }
    return header->next ? 0 : 1;
}
ND *slectNodeByVal(ND *header, int val)
{
    if (NULL == header)
    {
        puts("NULL list");
        exit(1);
    }
    while (header = header->next)
    {
        if (header->data == val)
        {
            return header;
        }
    }
    return NULL;
}
//init
void initList(ND *header){
    if (NULL == header)
    {
        puts("NULL list");
        return;
    }
    while (header->next)
    {
        ND * temp = header->next;
        header->next = temp->next;
        free(temp);
    }
    
}
//freeList
void freeList(ND **header){
    initList(*header);
    free(*header);
    *header = NULL;
}